package com.example.chatroom.api;

import com.example.chatroom.model.User;
import com.example.chatroom.model.UserMapper;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserAPI {
    @Resource
    UserMapper userMapper;
    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req){
        //键值对要匹配
        //首先查看username是否已经存在，能找到匹配密码
        User user=userMapper.selectByName(username);
        if (user == null||!user.getPassword().equals(password)) {
            //登录失败则打印空对象
        System.out.println("登录失败，用户名或密码错误->"+user);
        //在返回之前把对象的密码置空
        return new User();
        }
        //都匹配创建登录会话
        HttpSession session=req.getSession(true);
        session.setAttribute("user",user);
        user.setPassword("");
        return user;

    }
    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password){
        User user=null;
        try {
            //由于数据库里面用户名有unique约束不允许重复
            user=new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret= userMapper.insert(user);
            System.out.println("注册ret->"+ret);
            user.setPassword("");
        } catch (DuplicateKeyException e)
        {
            //如果insert方法抛出异常则说明重复，注册失败
            user=new User();
        }
        return user;
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req){
        //从已有会话获取会话
        HttpSession session=req.getSession();
        if (session == null) {
            System.out.println("获取不到当前对象，请检查登录");
            return new User();
        }
        //从会话中获取当前对象
        User user=(User)session.getAttribute("user");
        if (user == null) {
            System.out.println("获取不到当前对象，请检查登录");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
